/*
 * Copyright (c) 2015-2019, Texas Instruments Incorporated
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * *  Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * *  Neither the name of Texas Instruments Incorporated nor the names of
 *    its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <ti/posix/ccs/unistd.h>
#include <stdint.h>
#include <stddef.h>
#include <errno.h>

#include <ti/drivers/GPIO.h>

#include "ti_drivers_config.h"
#include "dbger.h"
#include "libmodbus/modbus.h"

#define SERVER_ID   (0x17)

extern "C" {
    #if defined(DBG_DISPLAY)
        extern void APP_openDisplay(void);
    #endif
    void *mainThread(void *arg0);
}

/*
 *  ======== mainThread ========
 */
void *mainThread(void *arg0)
{
    modbus_t *ctx;
    modbus_mapping_t *mb_mapping;

    GPIO_init();
    DBG_INIT();
    DBG_INFO("/************* Modbus Program Start **************/");

    GPIO_setConfig(CONFIG_GPIO_LED_0, GPIO_CFG_OUT_STD | GPIO_CFG_OUT_LOW);
    GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);

    ctx = modbus_new_rtu(UART2_Modbus, 115200, 'N', 8, 1);
    modbus_set_slave(ctx, SERVER_ID);
    modbus_set_debug(ctx, TRUE);

    //mb_mapping = modbus_mapping_new(200, 200, 200, 200);
    //mb_mapping = modbus_mapping_new(100, 100, 100, 100);
    mb_mapping = modbus_mapping_new_start_address(0, 100, 0, 100, 0, 100, 0, 100);
    if(mb_mapping == NULL) {
        DBG_ERROR("Failed to allocate the mapping!");
        modbus_free(ctx);
        while(1);
    }

    if(modbus_connect(ctx) == -1) {
        modbus_free(ctx);
        DBG_ERROR("Modbus connect failed!");
        while(1);
    }

    for (;;) {
        uint8_t query[MODBUS_RTU_MAX_ADU_LENGTH];
        int rc;

        rc = modbus_receive(ctx, query);
        if (rc > 0) {
            DBG_INFO("rc[%d]", rc);
            /* rc is the query size */
            modbus_reply(ctx, query, rc, mb_mapping);
            DBG_INFO("reply OK\n");
        } else if (rc == -1) {
            /* Connection closed by the client or error */
            DBG_ERROR("ERR: modbus_receive error.");
            break;
        }
    }

    DBG_INFO("Quit the loop: %s\n", modbus_strerror(errno));

    modbus_mapping_free(mb_mapping);
    modbus_close(ctx);      // TODO: close uart2
    modbus_free(ctx);

//    uint32_t time = 1;
//    while (1) {
//        sleep(time);
//        DBG_INFO("LED red toggle...");
//        GPIO_toggle(CONFIG_GPIO_LED_0);
//    }
    return NULL;
}
